package com.tank.jdk8.methodreference;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/1/26
 * Time: 19:31
 * To change this template use File | Settings | File Templates.
 */
public class MethodReferenceTest {


    public String getStr(String str, Function<String,String> function ){
        return function.apply(str);
    }

    public static void main(String[] args) {
        Animal animal = new Animal("cat",2);
        Animal animal2 = new Animal("dog",20);
        Animal animal3 = new Animal("snake",3);
//
        List<Animal> list = Arrays.asList(animal,animal2,animal3);

        // lamad
       // list.sort((param1,param2) -> Animal.comparatorByAge(param1,param2));

        //method reference
        /**方法签名一致
         * int compare(T o1, T o2);
         * int comparatorByAge(Animal animal,Animal animal2)
         */
        //类名::静态方法
        list.sort(Animal::comparatorByAge);


       // AnimalComparator animalComparator = new AnimalComparator();
     //   list.sort((param1,param2) -> animalComparator.comparatorByAge(param1,param2));
        // 引用名（对象）::实例方法名
      //  list.sort( animalComparator::comparatorByAge);

//        list.sort(Animal::comparatorAge);
//        list.forEach((a) -> System.out.println(a.getAge()));


//        List<String> cities = Arrays.asList("chengdu","anqing","shanghai");
//        //lambda express 排序
//        //sort 方法中Comparator参数的  int compare(T o1, T o2); 接受2个参数且无返回值
//        Collections.sort(cities,(city1,city2) -> city1.compareToIgnoreCase(city2));
//        //city1调用了compareToIgnoreCase方法，city2为compareToIgnoreCase方法的参数
//        Collections.sort(cities,String::compareToIgnoreCase);
//        cities.forEach(System.out::println);

        MethodReferenceTest methodReferenceTest = new MethodReferenceTest();
//        System.out.println(methodReferenceTest.getStr("hello",(str) -> {return str +" world";}));
        //1:执行算法语义由lambda传入
        //2：如果lambda express 只有一行代码可以不需要{}且不需要return，如果添加了{}则必须添加return
        System.out.println(methodReferenceTest.getStr("hello",(str) ->  str ));
        System.out.println(methodReferenceTest.getStr("hello",String::new));


    }
}

